package task

import (
	"io/fs"
	"path/filepath"
	"time"

	"file_explorer/common/consts"
	"file_explorer/common/log"
	"file_explorer/common/util"
	"file_explorer/model"
)

type PathWalker struct {
	BasicTask

	roots []*model.FileInfo

	refreshMs       int64
	lastRefreshTime time.Time
	onRefresh       func(root string, info *model.FileInfo)

	onAccess func(root string, info *model.FileInfo)
}

func (task *PathWalker) SetOnAccess(callback func(root string, info *model.FileInfo)) {
	task.onAccess = callback
}
func (task *PathWalker) SetOnRefresh(refreshMs int64, callback func(root string, info *model.FileInfo)) {
	task.refreshMs = refreshMs
	task.onRefresh = callback
}

func (task *PathWalker) start() {
	task.BasicTask.start()
	defer task.BasicTask.finish()

	log.Debug("path walker walk start")

	task.lastRefreshTime = task.startTime
	for _, root := range task.roots {
		// 文件直接累加
		if root.Type == consts.FileTypeRegular {
			task.onAccess(root.GetPath(), root)
			continue
		}

		// 目录dfs遍历
		rootPath := root.GetPath()
		filepath.WalkDir(rootPath, func(path string, entry fs.DirEntry, _ error) error {
			if !task.isRunning() {
				return nil
			}

			dir, _ := util.PathSplit(path)
			info := model.BuildFileInfo(dir, entry)
			task.onAccess(rootPath, info)
			now := time.Now()
			if task.refreshMs > 0 && now.Sub(task.lastRefreshTime).Milliseconds() >= task.refreshMs {
				task.onRefresh(rootPath, info)
				task.lastRefreshTime = now
			}

			return nil
		})

		if !task.isRunning() {
			break
		}
	}

	log.Debug("path walker walk end")
}

// path遍历
func NewPathWalker(roots []*model.FileInfo) *PathWalker {
	return &PathWalker{
		BasicTask: newBasicTask("path walker"),
		roots:     roots,
		onAccess:  func(root string, info *model.FileInfo) {},
		onRefresh: func(root string, info *model.FileInfo) {},
	}
}
